import { ref, type Ref } from 'vue'
import { useMutation } from '@tanstack/vue-query'

import { ApiPatchClassStudents, KeyClasses, classMessage } from '@/apis/class'
import { invalidateQueries } from '@/apis/client'
import { useFetchMessage } from '@/composables/useFetchMessage'
import type { PatchClassStudentsPayload } from '@/apis/class/types'
import { useToggle } from '@vueuse/core'

export function useStudentPatch(classID: Ref<number>) {
  const [visible, toggle] = useToggle()

  const { showMessage } = useFetchMessage([classMessage])
  const { mutate, isPending } = useMutation({
    mutationFn: (payload: PatchClassStudentsPayload) =>
      ApiPatchClassStudents(classID.value, payload),
    onSettled: (data, err) => showMessage(data?.code ?? err?.data?.code),
    onSuccess: () => {
      invalidateQueries(KeyClasses)
      toggle(false)
    }
  })

  const removeStudent = (student: string) => mutate([{ op: 'remove', value: [student] }])

  const selectedStudents = ref<string[]>([])
  const patchStudents = (op: 'add' | 'remove' | 'replace') => {
    mutate([{ op, value: selectedStudents.value }])
  }

  return {
    visible,
    toggle,
    isPending,
    selectedStudents,
    patchStudents,
    removeStudent
  }
}
